package com.web.system.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ModelDriven;
import com.util.BaseActionUtil;
import com.util.CommonUtil;
import com.util.JsonUtil;
import com.util.MD5Util;
import com.web.system.po.RolePo;
import com.web.system.po.UserPo;
import com.web.system.service.RoleService;
import com.web.system.service.UserService;

@Controller @Scope("prototype") 
@ParentPackage(value = "struts-default")
@Namespace(value = "/")
@Action(value = "userAction",results={
		@Result(name="input",type="redirect", location="/login.jsp")
})
public class UserAction extends BaseActionUtil implements ModelDriven<UserPo>{

	/**
	 * 
	 */
	private static final long serialVersionUID = -2193031151320102512L;
	@Resource
	private UserService userService;
	@Resource
	private RoleService roleService;
	
	private UserPo user;
	public UserPo getModel() {
		// TODO Auto-generated method stub
		user = new UserPo();
		return user;
	}

	
	public String getAllUser() throws Exception {
		
		String way = request.getParameter("way");
		UserPo userPo = (UserPo) session.getAttribute("user");
		List<UserPo> userPos = userService.getAllUsers(way , userPo);
		List<Map<String, Object>> jsonList = new ArrayList<Map<String,Object>>();
		for (int i = 0; i < userPos.size(); i++) {
			Map<String, Object> mapTemp = new HashMap<String, Object>();
			mapTemp.put("id", userPos.get(i).getUserId());
			mapTemp.put("text", userPos.get(i).getUserName());
			jsonList.add(mapTemp);
		}
		out.print(JsonUtil.objectToStr(jsonList));
		out.flush();
		out.close();
		return NONE;
	}
	 
	
	/**
	 * 用户名是否存在
	 * @return
	 * @throws Exception
	 */
	public String isExistUser() throws Exception{
		
		String way = request.getParameter("way");
		String name = request.getParameter("name");
		if("many".equals(way)){//发送邮件时候，输入的收件人验证
			out.print(userService.isExistUser(name) ? "1" : "0");
		} else{//新增用户验证
			out.print(userService.isExistUser(name) ? "0" : "1");
		}
		out.flush();
		out.close();
		return NONE;
	}
	/**
	 * 批量删除
	 * @return
	 * @throws Exception
	 */
	public String deleteUser() throws Exception {
		String ids = request.getParameter("ids");
		String []userIds = ids.split(",");
		UserPo userPoSession = (UserPo) session.getAttribute("user");
		for (int i = 1; i < userIds.length; i++) {
			if(userPoSession.getUserId().equals(userIds[i]) || "1".equals(userIds[i])){
				out.print("0");
				out.flush();
				out.close();
				return NONE;
			}
		}
		//String sql = "DELETE FROM UserPo as user WHERE user.userId IN ("+ ids +")";
		out.print(userService.deleteUsers(userIds));
		out.flush();
		out.close();
		return NONE;
	}
	
	/**
	 * 跟新管理账户
	 * @return
	 * @throws Exception
	 */
	
	public String updateUser() throws Exception {
		
		String erollTime_edit = request.getParameter("erollTime_edit");
		SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
		if(CommonUtil.isNotNull(erollTime_edit)){
			this.user.setErollTime(sdf.parse(erollTime_edit));
		}
		String loginTime_edit = request.getParameter("loginTime_edit");
		if(CommonUtil.isNotNull(loginTime_edit)){
			this.user.setLoginTime(sdf.parse(loginTime_edit));
		}
		
		
		this.user.setPassword(user.getPassword());
		String reset_password = request.getParameter("reset_password");
		if("1".equals(reset_password)){
			this.user.setPassword(MD5Util.getEncryptPsw("88888888"));
		}
		String roles_edit = request.getParameter("roles_edit");
		String []roleIds = roles_edit.split(",");
		
		List<RolePo> rolePos = new ArrayList<RolePo>();
		for (int i = 0; i < roleIds.length; i++) {
			RolePo rolePo = roleService.getRoleByRoleId(Integer.parseInt(roleIds[i]));
			rolePos.add(rolePo);
		}
		this.user.setRoleBeans(rolePos);
		this.user.setIsDelete(0);
   		out.print(userService.saveOrUpdateUser(user) ? "1" : "0");
   		out.flush();
   		out.close();
		return NONE;
	}
	
	
	/**
	 * 根据Id获取User
	 * @return
	 * @throws Exception
	 */
	public String getUserByUserId() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String userId = request.getParameter("userId");
		UserPo user = userService.getUserByUserId(userId);
        List<RolePo> rolePos = user.getRoleBeans();
        List<String> roleIds = new ArrayList<String>();
        for (RolePo rolePo : rolePos) {
        	roleIds.add(String.valueOf(rolePo.getRoleId()));
		}
        map.put("roleIds", roleIds);
		map.put("userSex", user.getUserSex());
		if("0".equals(user.getUserSex())){
			map.put("userSexName", "女");
		}else if("1".equals(user.getUserSex())){
			map.put("userSexName", "男");
		}
		map.put("user", user);
		out.print(JsonUtil.objectToStr(map,new String[]{"roleBeans"}));
		out.flush();
		out.close();
		return NONE;
	}
	
	/**
	 * 新增用户
	 * @return
	 * @throws Exception
	 */
	public String addUser() throws Exception {
		String roles = request.getParameter("roles");
		String []roleIds = roles.split(",");
		List<RolePo> rolePos = new ArrayList<RolePo>();
		for (int i = 0; i < roleIds.length; i++) {
			RolePo rolePo = roleService.getRoleByRoleId(Integer.parseInt(roleIds[i]));
			rolePos.add(rolePo);
		}
		this.user.setRoleBeans(rolePos);
		this.user.setErollTime(new Date());
		this.user.setPassword(MD5Util.getEncryptPsw("88888888"));
		this.user.setIsDelete(0);
		out.print(userService.saveOrUpdateUser(user) ? "1" : "0");
		out.flush();
		out.close();
		return NONE;
	}
	
	public boolean isAdmin(UserPo user){
		List<RolePo> rolePos = user.getRoleBeans();
		if(rolePos != null && rolePos.size() > 0){
			for (RolePo rolePo : rolePos) {
				if(rolePo.getRoleId() == 1){
					return true;
				}
			}
		}
		return false;
	}
	
	/**
	 * 分页显示数据
	 * @return
	 * @throws Exception
	 */
	public String getUserList() throws Exception {
		
		UserPo user = (UserPo) session.getAttribute("user");
		//分页部分
		int page = Integer.parseInt(request.getParameter("page"));
		int pageSize = Integer.parseInt(request.getParameter("rows"));
		int first = pageSize * (page - 1);
		String order = request.getParameter("order");
		String sort = request.getParameter("sort");
		
		//搜索部分
		String sql = " and user.isDelete = 0 ";
		String userNameSearch = request.getParameter("userNameSearch");
		String idCardSearch = request.getParameter("idCardSearch");
		String emailSearch = request.getParameter("emailSearch");
		String date_from = request.getParameter("date_from");
		String date_to = request.getParameter("date_to");
		if(emailSearch != null && !"".equals(emailSearch) && !"null".equals(emailSearch)){
			sql += " and user.email like '%"+emailSearch+"%'";
		}
		if(idCardSearch != null && !"".equals(idCardSearch) && !"null".equals(idCardSearch)){
			sql += " and user.idCard like '%"+idCardSearch+"%'";
		}
		if(userNameSearch != null && !"".equals(userNameSearch) && !"null".equals(userNameSearch)){
			sql += " and user.userName like '%"+userNameSearch+"%'";
		}
		if(date_from != null && !"".equals(date_from) && !"null".equals(date_from)){
			sql += " and user.erollTime >= '" + date_from + "'";
		}
		if(date_to != null && !"".equals(date_to) && !"null".equals(date_to)){
			sql +=" and user.erollTime <= '" + date_to + "'";
		}
		if(!isAdmin(user)){
			sql +=" and user.userId = '" + user.getUserId() + "'";
		}
		
		//组合最终sql语句
		StringBuffer queryStringBuffer = new StringBuffer();
		queryStringBuffer.append("FROM UserPo as user");
		queryStringBuffer.append(" left outer join fetch user.roleBeans ");
		queryStringBuffer.append(" where 1=1 ");
		queryStringBuffer.append(sql);
		queryStringBuffer.append(" ORDER BY  ");
		queryStringBuffer.append(sort);
		queryStringBuffer.append(" ");
		queryStringBuffer.append(order);
		
        List<UserPo> users = userService.getUserList(queryStringBuffer.toString(), first, pageSize);
        List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < users.size(); i++) {
        	Map<String, Object> map = new HashMap<String, Object>();
        	map.put("userId", users.get(i).getUserId());
        	map.put("userName", users.get(i).getUserName());
        	map.put("erollTime", users.get(i).getErollTime());
        	map.put("telephone", users.get(i).getTelephone());
        	map.put("idCard", users.get(i).getIdCard());
        	map.put("userSex", users.get(i).getUserSex());
        	map.put("birthday", users.get(i).getBirthday());
        	map.put("email", users.get(i).getEmail());
        	map.put("loginTime", users.get(i).getLoginTime());
        	List<RolePo> rList = users.get(i).getRoleBeans();
        	if(rList != null && rList.size() > 0){
            	StringBuffer roleListString = new StringBuffer();
            	for (RolePo rolePo : rList) {
            		roleListString.append(",");
            		roleListString.append(rolePo.getRoleName());
				}
            	if(roleListString != null){
            		map.put("roles", roleListString.toString().substring(1));
            	}
        	}
        	map.put("userId", users.get(i).getUserId());
        	map.put("address", users.get(i).getAddress());
        	userList.add(map);
		}
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        int total = userService.getTotal(sql);
        jsonMap.put("total", total);
        jsonMap.put("rows", userList);
        out.print(JsonUtil.objectToStr(jsonMap));
        out.flush();
        out.close();
		return NONE;
	}
	
	
	public void cancleUser() throws Exception {
		String longDate = request.getParameter("longDate");
		out.print(userService.cancleUser(longDate));
		out.flush();
		out.close();
	}
	
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}


}
